<?php
namespace app\admin\model;

use think\Db;
use think\facade\Config;
use think\Model;

class SmsReview extends Model
{
    public static function getListAll($request)
    {
        //检测表是否存在
        $tableName = 'bus_review_order_' . $request['st'];

        $tableResult = Db::query('SHOW TABLES LIKE ' . "'" . $tableName . "'");

        if ($tableResult && $request['cid'] != '') {
            //先查对应通道，没有直接过滤
            $platWhere[] = ['csc.onoff', 'eq', 1];
            $platWhere[] = ['csc.cid', 'eq', $request['cid']];
            if ($request['platId'] != '') {
                $platWhere[] = ['bp.plat_id', 'eq', $request['platId']];
            }
            $platInfo = Db::table('bus_channel_send_config')->alias('csc')
                ->field('bp.plat_id,bp.platfrom,csc.cid')
                ->join('bus_platfrom bp', 'bp.plat_id = csc.plat_id')
                ->where($platWhere)
                ->select();
            $plat = '';
            if ($platInfo) {
                foreach ($platInfo as $key => $value) {
                    $plat .= '<span class="layui-badge layui-bg-orange status-jy">' . $value['platfrom'] . '</span>&nbsp;';
                }

                $where[] = ['o.cid', 'eq', $request['cid']];

                if ($request['phone_type'] != '') {
                    $where[] = ['o.phone_type', 'eq', $request['phone_type']];
                }

                if ($request['create_time'] != '') {
                    $where[] = ['o.create_time', '> time', $request['create_time']];
                }

                if ($request['end_time'] != '') {
                    $where[] = ['o.create_time', '< time', $request['end_time']];
                }
                if ($request['state'] != '') {
                    $where[] = ['o.status', 'eq', $request['state']];
                }

                if ($request['channel_order_id'] != '') {
                    $where[] = ['o.channel_order_id', 'eq', $request['channel_order_id']];
                }
                if ($request['send_text'] != '') {
                    $where[] = ['o.send_text', 'like', '%' . $request['send_text'] . '%'];
                }
                if ($request['phone'] != '') {
                    $where[] = ['rp.phone', 'eq', $request['phone']];
                }

                if ($request['isp_host'] != '') {
                    $where[] = ['rp.isp', 'eq', $request['isp_host']];
                }

                $data = Db::table($tableName)->alias('o')
                // ->field('o.*,c.company_name,cs.isp_host, sum(case when rp.phone=' . $phone . ' then 1 else 0 end) as phone_number')
                    ->field('o.*,rp.phone,c.company_name')

                    ->join('bus_channel c', 'o.cid = c.channel_id')

                    ->join('bus_review_phone_' . $request['st'] . ' rp', 'rp.table_order_id = o.id', 'RIGHT')
                    ->where($where)
                    ->group('o.id')
                    ->paginate($request['limit'], false, $request)
                    ->toarray();

                foreach ($data['data'] as $k => $v) {
                    //查询渠道对应的通道
                    switch ($v['result']) {
                        case '0':
                            $data['data'][$k]['result'] = '<span class="layui-badge layui-bg-orange status-jy">等待处理</span>';
                            break;
                        case '1':
                            $data['data'][$k]['result'] = '<span class="layui-badge layui-bg-green status-qy">已处理</span>';
                            break;
                        default:
                            $data['data'][$k]['result'] = '未定义';
                            break;
                    }
                    switch ($v['phone_type']) {
                        case '0':
                            $data['data'][$k]['phone_type'] = '<span class="layui-badge layui-bg-blue status-jy">群发</span>';
                            break;
                        case '1':
                            $data['data'][$k]['phone_type'] = '<span class="layui-badge layui-bg-green status-qy">单发</span>';
                            break;
                        default:
                            $data['data'][$k]['phone_type'] = '未定义';
                            break;
                    }
                    switch ($v['status']) {
                        case '0':
                            $data['data'][$k]['status'] = '<span class="layui-badge layui-bg-orange status-jy">待审核</span>';
                            break;
                        case '1':
                            $data['data'][$k]['status'] = '<span class="layui-badge layui-bg-green status-qy">通过</span>';
                            break;
                        case '2':
                            $data['data'][$k]['status'] = '<span class="layui-badge status-qy">失败</span>';
                            break;
                        default:
                            $data['data'][$k]['status'] = '未定义';
                            break;
                    }
                    switch ($v['submit_type']) {
                        case '0':
                            $data['data'][$k]['submit_type'] = '<span class="layui-badge layui-bg-orange status-jy">http</span>';
                            break;
                        case '1':
                            $data['data'][$k]['submit_type'] = '<span class="layui-badge layui-bg-cyan status-qy">cmpp</span>';
                            break;
                        default:
                            $data['data'][$k]['submit_type'] = '未定义';
                            break;
                    }

                    $data['data'][$k]['phone_size'] = '<a href="javascript:;" onclick="open_window(\'查看号码\',\'/admin/sms_review/smsPhone.html\',\'?table_order_id=' . $v['id'] . '&st=' . $request['st'] . '\',\'600\',\'400\')" style="color: #3498db;">查看号码</a>';

                    $data['data'][$k]['company_name'] = $data['data'][$k]['company_name'] . '(' . $data['data'][$k]['cid'] . ')';
                    $data['data'][$k]['plat']         = $plat;
                }

            } else {
                $data['total'] = 0;
                $data['data']  = [];
            }

        } else {
            $data['total'] = 0;
            $data['data']  = [];
        }

        return $data;

    }

    /**
     * [reviewSms 审核短信]
     * @param  [type] $request [description]
     * @return [type]          [description]
     */
    public static function reviewSms($request)
    {
        //检测表是否存在
        $tableName = 'bus_review_order_' . $request['st'];

        $tableResult = Db::query('SHOW TABLES LIKE ' . "'" . $tableName . "'");

        if ($tableResult) {
            $where[] = ['status', 'eq', 0];
            $where[] = ['id', 'In', json_decode($request['reviewId'], true)];
            $where[] = ['cid', 'eq', $request['cid']];
            $batchId = uniqid();
            $data    = [
                'desc'        => $request['desc'],
                'status'      => $request['status'],
                'batch_id'    => $batchId,
                'review_time' => date('Y-m-d H:i:s'),
                'username'    => session('username'),
            ];
            trace('表' . $tableName . '--审核短信--id:' . $request['reviewId']);
            Db::startTrans();
            try {
                $updateResult = Db::table($tableName)->where($where)->update($data);
                if ($updateResult != false) {
                	// 提交事务
                    Db::commit();
                    // $url         = 'http://183.240.150.13:3389/SMS/review/';
                    $url         = Config::get('SMS_REVIEW');
                    $requestData = [
                        'tableDate' => $request['st'],
                        'cid'       => $request['cid'],
                        'batchId'   => $batchId,
                        'type'      => $request['phone_type'],
                    ];
                    trace('短信审核请求java--' . json_encode($requestData));
                    $javaResult = curl_post($url, $requestData);
                    trace('请求返回---' . json_encode($javaResult));
                    
                    $result = ['code' => 200, 'msg' => '处理成功'];
                } else {
                    Db::rollback();
                    $result = ['code' => 422, 'msg' => '不存在需要审核的短信'];
                }
                //请求java
            } catch (\Exception $e) {
                trace('短信审核报错---' . $e);
                // 回滚事务
                Db::rollback();
                $result = ['code' => 422, 'msg' => '处理失败'];
            }

        } else {
            $result = ['code' => 422, 'msg' => '不存在该数据表'];
        }

        return $result;

    }

    /**
     * [batchReviewSms 批量审核短信]
     * @param  [type] $request [description]
     * @return [type]          [description]
     */
    public static function batchReviewSms($request)
    {
        //先查对应通道，没有直接过滤
        $platWhere[] = ['csc.onoff', 'eq', 1];
        $platWhere[] = ['csc.cid', 'eq', $request['cid']];
        if ($request['platId'] != '') {
            $platWhere[] = ['bp.plat_id', 'eq', $request['platId']];
        }
        $platInfo = Db::table('bus_channel_send_config')->alias('csc')
            ->field('bp.plat_id,bp.platfrom,csc.cid')
            ->join('bus_platfrom bp', 'bp.plat_id = csc.plat_id')
            ->where($platWhere)
            ->select();
        //审核表
        $tableName = 'bus_review_order_' . $request['st'];

        $tableResult = Db::query('SHOW TABLES LIKE ' . "'" . $tableName . "'");

        if ($platInfo && $request['cid'] != '' && is_numeric($request['number']) && $tableResult) {

            $where[] = ['o.status', 'eq', 0];
            $where[] = ['o.cid', 'eq', $request['cid']];
            if ($request['phone_type'] != '') {
                $where[] = ['o.phone_type', 'eq', $request['phone_type']];
            }

            if ($request['create_time'] != '') {
                $where[] = ['o.create_time', '> time', $request['create_time']];
            }

            if ($request['end_time'] != '') {
                $where[] = ['o.create_time', '< time', $request['end_time']];
            }

            if ($request['channel_order_id'] != '') {
                $where[] = ['o.channel_order_id', 'eq', $request['channel_order_id']];
            }
            if ($request['send_text'] != '') {
                $where[] = ['o.send_text', 'like', '%' . $request['send_text'] . '%'];
            }
            if ($request['phone'] != '') {
                $where[] = ['rp.phone', 'eq', $request['phone']];
            }

            if ($request['isp'] != '') {
                $where[] = ['rp.isp', 'eq', $request['isp']];
            }

            $orderIdArr = Db::table($tableName)->alias('o')
                ->field('o.*,rp.phone,c.company_name')

                ->join('bus_channel c', 'o.cid = c.channel_id')
                ->join('bus_review_phone_' . $request['st'] . ' rp', 'rp.table_order_id = o.id')
                ->where($where)
                ->group('o.id')
                ->limit($request['number'])
                ->column('o.id');
            trace('批量更新表' . $tableName . '----id:' . json_encode($orderIdArr));
            if ($orderIdArr) {
                $batchId = uniqid();
                $data    = [
                    'desc'        => $request['desc'],
                    'status'      => $request['status'],
                    'batch_id'    => $batchId,
                    'review_time' => date('Y-m-d H:i:s'),
                    'username'    => session('username'),
                ];
                Db::startTrans();
                try {
                    $updateResult = Db::table($tableName)->where('id', 'IN', $orderIdArr)->where('status', 'eq', 0)->where('cid', 'eq', $request['cid'])->update($data);
                    if ($updateResult != false) {
                    	// 提交事务
                        Db::commit();
                        // $url         = 'http://183.240.150.13:3389/SMS/review/';
                        $url         = Config::get('SMS_REVIEW');
                        $requestData = [
                            'tableDate' => $request['st'],
                            'cid'       => $request['cid'],
                            'batchId'   => $batchId,
                            'type'      => $request['phone_type'],
                        ];
                        trace('批量审核请求java--' . json_encode($requestData));
                        $javaResult = curl_post($url, $requestData);
                        trace('批量请求返回---' . json_encode($javaResult));
                        
                        $result = ['code' => 200, 'msg' => '处理成功'];
                    } else {
                        Db::rollback();
                        $result = ['code' => 422, 'msg' => '不存在需要审核的短信'];
                    }
                    //请求java
                } catch (\Exception $e) {
                    trace('批量短信审核报错---' . $e);
                    // 回滚事务
                    Db::rollback();
                    $result = ['code' => 422, 'msg' => '处理失败'];
                }

            }
        } else {
            $result = ['code' => 422, 'msg' => '无需要审核的短信'];
        }

        return $result;

    }

}
